package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.http.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.db.entity.RunningStrategyExt;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.DtuPushTypeEnum;
import com.mingqijia.gassafety.shared.handler.GlobalAuthenticationException;
import com.mingqijia.gassafety.webserver.dto.CallTaskDTO;
import com.mingqijia.gassafety.webserver.service.DictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @program: gassafety
 * @description: 接入讯飞外呼
 * http://docs-platform.mingqijia.com/#/call-service/app/create
 * @author: Mr.Wang
 * @create: 2023-02-13 13:38
 **/
@Component
@Slf4j
public class XFCallServiceImpl {


    @Value(value = "${gassafety.xf.call.appKey}")
    public String appKey;

    @Value(value = "${gassafety.xf.call.appSecret}")
    public String appSecret;

    @Value(value = "${gassafety.xf.call.url}")
    public String callServerUrl;

    @Value(value = "${gassafety.xf.call.robotId}")
    public String robotId;

    @Value(value = "${gassafety.xf.call.appId}")
    public Integer appId;

    @Autowired
    public DictionaryService dictionaryService;

    //语音音色
   /* 春春	65580	女声
    晓诗	62140	女声
    晓燕	60020	女声
    晓峰	60030	男声
    小陈	65660	男声
    楠楠	60130	女声
    晓医	65600	女声*/
    private static final String voiceCode = "62360";
    private static final String callColumn = "[\"客户手机号码\",\"安装地址\",\"燃气公司名\",\"公司电话\"]";
    //线路号码
    private static final String lineNum = "65008475";

    private static final String taskCode = "gassafety_call_task";
    // required 讯飞 task_name
    private static final String taskName = "报警器外呼机器人";




    //app查询创建和更新
    private static final String APP_SEARCH = "%s/api/app/search";
    private static final String APP_CREATE = "%s/api/app/create";
    private static final String APP_UPDATE = "%s/api/app/update";
    // 任务池添加
    private static final String TASK_POOL_ADD = "%s/api/TaskPool/add";
    //任务池更新
    private static final String TASK_POOL_UPDATE = "%s/api/TaskPool/Update";
    //进行呼叫
    private static final String CALL_CREATE = "%s/api/call/create";
    //进行呼叫池创建
    private static final String CALL_POOL_CREATE = "%s/api/call/poolCreate";
    //呼叫历史查询
    private static final String CALL_SEARCH = "%s/api/call/search";



    //查询呼叫结果
    public JSONObject callSearch(CallTaskDTO dto){
        log.info("调用基础服务-外呼机器人-查询呼叫结果");
        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(CALL_SEARCH, callServerUrl));
        Map<String, Object> params = new HashMap<>();
        params.put("ids",dto.getTaskDataId());
        params.put("page",1);
        params.put("page_size",50);

        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());
        log.info("查询呼叫结果,入参:{}",JSONObject.toJSONString(params));

        Object object = doHttpRequest(request);
        JSONObject json =  (JSONObject) object;
//        log.info(json.toString());
        return json;
    }



    //进行呼叫
    public JSONObject callCreate(CallTaskDTO dto, String spId){
        log.info("调用基础服务-外呼机器人-呼叫");

        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(CALL_CREATE, callServerUrl));
        Map<String, Object> params = new HashMap<>();
        if (dto.getAppId()==null){
            params.put("app_id",appId);
        }else {
            params.put("app_id",dto.getAppId());
        }

        String configChannel =  dictionaryService.getChannel(spId);
        if (!StringUtils.isEmpty(configChannel)){
            params.put("task_code",configChannel);
        }else {
            params.put("task_code",taskCode);
        }
        if (!CollectionUtils.isEmpty(dto.getCallColumn())){
            params.put("call_column",dto.getCallColumn());
        }else {
            params.put("call_column",JSONArray.parseArray(callColumn));
        }
        if (!StringUtil.isEmpty(dto.getTaskCode())){
            params.put("task_code",dto.getTaskCode());
        }
        params.put("call_list", JSONArray.parseArray(JSONObject.toJSONString(dto.getCallList())));
        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());
        log.info("呼叫,入参:{}, request:{}",JSONObject.toJSONString(params), JSONObject.toJSONString(request));

        Object object = doHttpRequest(request);
        JSONObject json =  (JSONObject) object;
        return json;
    }

    public JSONObject callPoolCreate(CallTaskDTO dto, String spId){
        log.info("调用基础服务-外呼机器人-呼叫信息创建");
        log.info("callCreate-param:{},{}",JSONObject.toJSONString(dto),spId);

        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(CALL_POOL_CREATE, callServerUrl));
        Map<String, Object> params = new HashMap<>();
        if (dto.getAppId()==null){
            params.put("app_id",appId);
        }else {
            params.put("app_id",dto.getAppId());
        }

        String configChannel =  dictionaryService.getChannel(spId);
        if (!StringUtils.isEmpty(configChannel)){
            params.put("task_code",configChannel);
        }else {
            params.put("task_code",taskCode);
        }
        if (!CollectionUtils.isEmpty(dto.getCallColumn())){
            params.put("call_column",dto.getCallColumn());
        }else {
            params.put("call_column",JSONArray.parseArray(callColumn));
        }
        if (!StringUtil.isEmpty(dto.getTaskCode())){
            params.put("task_code",dto.getTaskCode());
        }
        if (!StringUtil.isEmpty(dto.getExecTimeStart()) && !StringUtil.isEmpty(dto.getExecTimeEnd())) {
            params.put("exec_time_start", dto.getExecTimeStart().trim());
            params.put("exec_time_end", dto.getExecTimeEnd().trim());
        }
        params.put("call_list", JSONArray.parseArray(JSONObject.toJSONString(dto.getCallList())));
        log.info("呼叫,入参:{}",JSONObject.toJSONString(params));
        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());

        Object object = doHttpRequest(request);
        JSONObject json =  (JSONObject) object;
        return json;
    }


    //任务池更新
    public JSONObject taskPoolUpdate(CallTaskDTO dto){
        log.info("调用基础服务-外呼机器人-任务池更新");
//        dto.setAppId(appId); // 注册后拿到appid
//        dto.setOrgCode("gassafety");
//        dto.setRobotId(robotId);
//        dto.setLineNum(lineNum);  //线路号码是需要在讯飞后台进行配置
//        dto.setVoiceCode(voiceCode);
//        dto.setCallColumn(JSONArray.parseArray(callColumn));
        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(TASK_POOL_UPDATE, callServerUrl));

        Map<String, Object> params = new HashMap<>();
        params.put("id",dto.getId());
        params.put("app_id",dto.getAppId());
        params.put("org_code",dto.getOrgCode());
        String configChannel =  dictionaryService.getChannel();
        params.put("task_code",dto.getTaskCode());
        params.put("task_name",dto.getTaskName());
        params.put("robot_id",dto.getRobotId());
        params.put("line_num",dto.getLineNum());
        params.put("voice_code",dto.getVoiceCode());
        params.put("call_column", dto.getCallColumn());
        log.info("任务池更新,入参:{}",JSONObject.toJSONString(params));

        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());

        Object object = doHttpRequest(request);
        JSONObject data = new JSONObject();
        data.put("successCount", object);
        return data;
    }

    // 任务池添加
    public JSONObject tackPoolAdd(CallTaskDTO dto){

        log.info("调用基础服务-外呼机器人-任务池创建");
//        dto.setAppId(appId); // 注册后拿到appid
//        dto.setOrgCode("gassafety");
//        dto.setRobotId(robotId);
//        dto.setLineNum(lineNum);  //线路号码是需要在讯飞后台进行配置
//        dto.setVoiceCode(voiceCode);
//        dto.setCallColumn(JSONArray.parseArray(callColumn));
        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(TASK_POOL_ADD, callServerUrl));

        Map<String, Object> params = new HashMap<>();
        params.put("app_id",dto.getAppId());
        params.put("org_code",dto.getOrgCode());
        String configChannel =  dictionaryService.getChannel();

        params.put("task_code",dto.getTaskCode());
        params.put("task_name",dto.getTaskName());
        params.put("robot_id",dto.getRobotId());
        params.put("line_num",dto.getLineNum());
        params.put("voice_code",dto.getVoiceCode());
        params.put("call_column", dto.getCallColumn());
        log.info("任务池创建,入参:{}",JSONObject.toJSONString(params));
        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());

        Object object = doHttpRequest(request);
        JSONObject data = new JSONObject();
        data.put("taskPoolId", object);
        return data;
    }


    
    //app查询
    public JSONObject appSearch(String appName){
        log.info("调用基础服务-外呼机器人-app查询");
        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(APP_SEARCH, callServerUrl));
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name",appName);
        params.put("page", 1);
        params.put("page_size", 9999);
        log.info("app查询,入参:{}",JSONObject.toJSONString(params));
        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());
        JSONObject object = (JSONObject)doHttpRequest(request);
        return object;
    }
 
    //app创建
    public JSONObject appCreate(String appName,String appKey,String appSecret){
        log.info("调用基础服务-外呼机器人-app创建");
        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(APP_CREATE, callServerUrl));
        Map<String, String> params = new HashMap<String, String>();
        params.put("name",appName);
        params.put("key",appKey);
        params.put("secret",appSecret);
        log.info("app创建,入参:{}",JSONObject.toJSONString(params));
        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());
        Object object = doHttpRequest(request);
        JSONObject data = new JSONObject();
        data.put("appId", object);
        return data;

    }

    //app 更新
    public Integer appUpdate(String appName, Integer appId){
        log.info("调用基础服务-外呼机器人-app更新");
        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(APP_UPDATE, callServerUrl));
        Map<String, Object> params = new HashMap<>();
        params.put("name",appName);
        params.put("id",appId);
        params.put("key",appKey);
        params.put("secret",appSecret);
        log.info("app创建,入参:{}",JSONObject.toJSONString(params));
        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());
        return (Integer) doHttpRequest(request);

    }


    public Integer appUpdate(String appName, Integer appId, String key, String secret){
        log.info("调用基础服务-外呼机器人-app更新");
        HttpRequest request = HttpUtil.createRequest(Method.POST,
                String.format(APP_UPDATE, callServerUrl));
        Map<String, Object> params = new HashMap<>();
        params.put("name",appName);
        params.put("id",appId);
        params.put("key",key);
        params.put("secret",secret);
        log.info("app创建,入参:{}",JSONObject.toJSONString(params));
        request.body(JSONObject.toJSONString(params), ContentType.JSON.getValue());
        return (Integer) doHttpRequest(request);

    }


    private Object doHttpRequest(HttpRequest request) {
        HttpResponse response = request.execute();
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            log.error("调用{}失败, 返回：{}", request.getUrl(), response.body());
            throw new GlobalAuthenticationException(response.body());
        }
        log.info("调用{}, 返回:{}", request.getUrl(), response.body());
        JSONObject result = JSONObject.parseObject(response.body());
        if (!Objects.equals(result.getInteger("code"), Constants.INT_ZERO)) {
            log.error("数据请求失败：{}", response.body());
            throw new GlobalAuthenticationException(result.getString("msg"));
        }
        return result.get("data");
    }

    public CallTaskDTO addCallExecTimeParam(CallTaskDTO callTaskDTO, RunningStrategyExt ext){
        if(!ObjectUtils.isEmpty(ext)){
            DtuPushTypeEnum dtuPushTypeEnum = DtuPushTypeEnum.getPushTypes(ext.getPushTime());
            if (null!=dtuPushTypeEnum) {
                String[] pushTimes = dtuPushTypeEnum.getTypes();
                callTaskDTO.setExecTimeStart(pushTimes.length==2?pushTimes[0]+":00":"08:00:00");
                callTaskDTO.setExecTimeEnd(pushTimes.length==2?pushTimes[1]+":00":"22:00:00");
            }
        }
        return callTaskDTO;
    }
}
